package assg.funnycells.cells;

import assg.funnycells.util.*;
import java.io.*;

public class EnergyCellImpl implements CellularProcesses, Runnable {
    int x, y;
    int type;
    String cellId;
    RateLimPrintWriter out;
    RateLimBufferedReader in;
    long timeout;
    String chemStr;
    Logger logger;

    Boolean socOk = true;

    public EnergyCellImpl(Integer type, Integer energy, String cellId, RateLimBufferedReader in, RateLimPrintWriter out) {
	this.type = type;
	this.cellId = cellId;
	this.out = out;
	this.in = in;
	this.logger = Logger.getDefaultLogger();

	Configuration config = FunnyCell.getConfiguration();
	this.chemStr = config.getVal(Configuration.RECEPTORS, Configuration.START) +
	    config.getVal(Configuration.RECEPTORS, Configuration.ANY) +
	    config.getVal(Configuration.AFFECTORS, Configuration.ENERGY) +
	    config.getVal(Configuration.RECEPTORS, Configuration.STOP);
	this.timeout = config.getIntVal(Configuration.PARAMS, Configuration.MOLTIMEOUT) * chemStr.length() -
	    config.getIntVal(Configuration.PARAMS, Configuration.JIGGLE);
	
	this.x = config.getIntVal(Configuration.MAP, Configuration.WIDTH) / 2;
	this.y = config.getIntVal(Configuration.MAP, Configuration.HEIGHT) / 2;

    }

    public void startCell() {
	Thread t = new Thread(this);
	t.start();

	while(true) {
	    out.println(assg.funnycells.server.Cell.MOVECELL);
	    out.println("incx=" + 0);
	    out.println("incy=" + 0);
	    out.println("");
	    out.println(assg.funnycells.server.Cell.DROPENERGY);
	    out.println(chemStr);
	    out.println("x=" + x);
	    out.println("y=" + y);
	    out.println("");
	    out.flush();
	    
	    try { Thread.sleep(timeout); } catch(Exception e) { }

	    synchronized(socOk) {
		if(!socOk)
		    break;
	    }
	}
    }

    public void run() {
	String readline;
	boolean xCoordRead = false;
	boolean yCoordRead = false;
	
	while(true) {
	    try {
		if((readline = in.readLine()) == null) break;
		logger.debug("* readline: " + readline);
		if(!xCoordRead && readline.startsWith("x=")) {
		    x = StringOperations.parseInt(StringOperations.parseVal(readline));
		    if(x > -1)
			xCoordRead = true;
		} else if(!yCoordRead && readline.startsWith("y=")) {
		    y = StringOperations.parseInt(StringOperations.parseVal(readline));
		    if(y > -1)
			yCoordRead = true;
		}
	    } catch(Exception e) {
		logger.error("Cell crash", e);
		break;
	    }
	}

	synchronized(socOk) {
	    socOk = false;
	}
	
	try {
	    in.close();
	} catch(Exception e) { }
    }

}